import React from 'react';
import { Button } from 'antd';
import { connect } from '@/dva';
import EditContent from './edit';
import Cards from './components/Cards';
import { ConnectProps } from '@/dva/types';
import { ModalPro, SearchPro } from '@/components';
import { FormItem } from '@/components/FormPro/types';
import { State as SourceState } from '@/models/imageSource/types';
import { ListItem as ClassifyItem } from '@/service/image/getClassifyList';

type Props = ConnectProps & {
  imageSource: SourceState;
  classifyItem: ClassifyItem;
}

@connect({
  imageSource: ({ imageSource }) => imageSource
})
class ImageContent extends React.PureComponent<Props> {
  static defaultProps = {
    imageSource: {},
    classifyItem: {}
  }

  query: any = {};

  get classify() {
    const {
      classifyItem
    } = this.props
    return classifyItem._id;
  }

  get pageSource() {
    const {
      pageMap = {}
    } = this.props.imageSource;
    return pageMap[this.classify] || {};
  }

  get dataSource() {
    return this.pageSource?.list || [];
  }

  get loading() {
    return this.pageSource?.loading;
  }

  get pagination() {
    return this.pageSource?.pagination || {};
  }

  async componentDidMount() {
    await this.fetchList();
  }

  private onSearch = async (query: any = {}) => {
    this.query = query;
    await this.fetchList();
  }

  private onPageChange = (page: number) => this.fetchList(page);

  private fetchList = async (page: number = 1) => {
    const params: any = { ...this.query, classify: this.classify, page, limit: 24 };
    this.props?.commit?.('imageSource/fetchImageList', params);
  }

  render() {
    const {
      classifyItem
    } = this.props;

    const formList: FormItem[] = [{
      type: 'input',
      name: 'name',
      label: '图片名称'
    }];

    const content = (
      <EditContent
        onSuccess={this.fetchList}
        classifyItem={classifyItem}
      />
    );

    return (
      <React.Fragment>
        <SearchPro
          formList={formList}
          onSearch={this.onSearch}
        >
          <ModalPro
            width="400px"
            title="新建图片"
            okText="新建"
            cancelText="取消"
            triggerContent={content}
            children={<Button children="新建"/>}
          />
        </SearchPro>
        <Cards
          loading={this.loading}
          dataSource={this.dataSource}
          pagination={this.pagination}
          onPageChange={this.onPageChange}
        />
      </React.Fragment>
    )
  }
}

export default ImageContent;
